# -*- coding: utf-8 -*-

# $Id: entry_points.py 2 2012-09-01 15:54:17Z alexis.roda.villalonga@gmail.com $

import pkg_resources

from dja_skel.lib import errors


UNSPECIFIED = []


_entry_points_cache = {}


def load_first_entry_point(group, name) :
    """Locates an entry point.

    Locates the entry points in the group ``group`` matching the name
    ``name``. Returns the object referenced by the first match.

    If something goes wrong while locating or loading the entry point
    an ``SkelError`` exception is raised.

    That function uses a cache so that requests for an already loaded
    entry point will be served from memory, skipping the locate and
    load phases.
    """
    key = "%s:%s" % (group, name)
    if key not in _entry_points_cache :
        ep_it = pkg_resources.iter_entry_points(group, name)
        try:
            ep = ep_it.next()
        except StopIteration :
            raise errors.SkelError(
                "Entry point '%s:%s' not found" % (group, name)
                )
        try:
            ep_obj = ep.load()
        except ImportError :
            raise errors.SkelError(
                "Error logding '%s' from '%s'"
                % (name, ep.module_name)
                )
        _entry_points_cache[key] = ep_obj
    return _entry_points_cache[key]
